package main

import (
	"errors"
	"gitee.com/showurl/push-rtmp/config"
	"gitee.com/showurl/push-rtmp/utils"
	"gorm.io/gorm"
	"log"
	"os"
)

func main() {
	go func() {
		utils.GetBarrage()
	}()
	var (
		rtmpAddress = os.Getenv("LIVE_HOST") + os.Getenv("LIVE_KEY")
	)
	for {
		nowMp4, err := getNowMp4()
		if err != nil {
			if errors.Is(err, gorm.ErrRecordNotFound) {
				err = nil
			} else {
				panic(err)
			}
		}
		var startIndex int
		if nowMp4.ID != 0 {
			for i, mp4Path := range config.Config.Playlist {
				if mp4Path == nowMp4.Mp4Path {
					if nowMp4.HealthSeconds < nowMp4.Seconds-config.Config.HealthInterval*2 {
						// 没播完
						startIndex = i
					} else {
						if i == len(config.Config.Playlist)-1 {
							// 已经是最后一个了
							// 那还是0
						} else {
							if i < len(config.Config.Playlist)-1 {
								// 不是最后一个
								startIndex = i + 1
							}
						}
					}
				}
			}
		}
		for i, mp4Path := range config.Config.Playlist {
			if i != startIndex {
				continue
			}
			ticker, err := play(mp4Path, rtmpAddress)
			if err != nil {
				if ticker != nil {
					ticker.Stop()
				}
				log.Println("错误:", err.Error())
				break
			}
		}
	}
}
